<template>
  <div class="page-content">
    <MenuBar v-if="!isMobile" passTab="36" />

    <PhoneMenuBar v-else passTab="36" />

    <div style="height: 70px;"></div>

    <div class="page-product">
      <div class="product-title">网站留言</div>


      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>


      <div class="message-layout">

        <n-list size="large" :style="{ 'width': isMobile ? '100%' : '60%' }">
          <n-list-item v-for="item in all_newsList" v-bind:key="item.id">

            <div class="item-layout" :style="{ 'min-height': isMobile ? '100px' : '150px' }">


              <div class="header-layout">

                <img src="@/assets/images/png/头像.png" style="width: 36px;height: 36px;" />

                <div style="margin-left: 15px;">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-descript" v-if="!isMobile">{{ item.content }}</div>
                </div>

                <div style="flex: 1;"></div>

                <div class="item-time">{{ item.addTime2 }}</div>
              </div>

              <div class="item-descript" v-if="isMobile">{{ item.content }}</div>


              <div class="item-reply">站长回复：{{ item.useinfo }}</div>

            </div>

          </n-list-item>
        </n-list>

        <div v-if="isMobile && pageNum != totalNum"
          style="display: flex;justify-content: space-between;align-items: center;margin-top: 15px;">

          <n-button type="info" @click="pageNumOnClick('-')"
            :style="{ visibility: pageNum != 1 ? 'visible' : 'hidden' }">
            上一页
          </n-button>

          <div style="width: 80px;"><n-select v-model:value="pageNum" @update:value="handlePageNumValue"
              :options="pageNumOptions" filterable /></div>

          <n-button type="info" @click="pageNumOnClick('+')"
            :style="{ visibility: pageNum != totalNum ? 'visible' : 'hidden' }">
            下一页
          </n-button>
        </div>

        <div style="width: 15px;" v-if="!isMobile"></div>

        <div class="reply-board">
          <div class="reply-title"><n-icon size="20" color="#111111">
              <Create />
            </n-icon>
            <div style="margin-left: 5px;">我要留言</div>
          </div>
          <n-space vertical :size="15" v-if="fieldsTitle.length">
            <n-input type="text" size="large" v-model:value="name" :placeholder="fieldsTitle[0]?.name" />

            <n-input type="text" size="large" v-model:value="wechat" :placeholder="fieldsTitle[1]?.name" />

            <n-input v-model:value="content" rows="5" size="large" type="textarea"
              :placeholder="fieldsTitle[2]?.name" />



            <n-input clearable v-model:value="verifyCode" placeholder="验证码" size="large" :maxlength="4">
              <template #suffix>
                <VerifyCode ref="captchaRef" @click="setCodeVerify()" />
              </template>

            </n-input>

            <n-button style="width: 100%;background-color: #000000;font-style: 18px;color: white;padding: 25px;"
              @click="uploadBoard()" size="large">
              提交留言
            </n-button>


          </n-space>



        </div>

      </div>


      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange1" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>

    </div>

    <BottomBar />
  </div>
</template>

<script setup name="productListPage">
import { useDialog } from 'naive-ui';
import { Create } from '@vicons/ionicons5'
import { API_URL } from '@/config'
import { messageList, fieldsList, getCode, submit } from '@/api'
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import MenuBar from '@/components/MenuBar.vue'
import PhoneMenuBar from '@/components/PhoneMenuBar.vue'
import BottomBar from '@/components/BottomBar.vue'
import VerifyCode from '@/components/VerifyCode.vue'
// 创建一个响应式变量来存储是否为移动设备
const isMobile = ref(false);

// 定义一个函数来检查用户代理
const checkDevice = () => {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // 设置isMobile的值
  isMobile.value = /android/i.test(userAgent) || /iPhone|iPad|iPod/i.test(userAgent);
};





const all_newsList = ref([])
const totalNum = ref(0)
const pageSize = 10
const getNewsList = async () => {
  const params = {
    page: pageNum.value,
    size: pageSize,
    module: 7
  }
  const result = await messageList(params)

  console.log("newsList", result)

  if (result != null && result.data != null) {

    // if (typeId.value == -1) {
    //   all_newsList.value = result.data
    // } else {
    //   all_newsList.value = result.data.reverse()
    // }

    all_newsList.value = result.data.map(item => {
      return {
        ...item,
        addTime2: item.addtime.length > 10 ? item.addtime.split(' ')[0] : item.addtime
      }
    })

    const totalCount = result.total;

    const fullPages = Math.floor(totalCount / pageSize); // 完整页数
    const remainder = totalCount % pageSize;             // 余数

    totalNum.value = remainder > 0 ? fullPages + 1 : fullPages;

    pageNumOptions.value = []
    for (let i = 1; i <= totalNum.value; i++) {
      pageNumOptions.value.push({ label: i + "", value: i + "" })
    }

  }
}

var myUuid = ""
async function setCodeVerify() {
  myUuid = crypto.randomUUID();
  const result1 = await getCode({
    uuid: myUuid,
    res_format_type: "string",
  })
  if (result1.data) {
    console.log("verifyCodeValue", result1.data)
    const verifyCodeValue = result1.data

    captchaRef.value.setVerifyCode(verifyCodeValue)
  }
}

const fieldsTitle = ref([])
const route = useRoute()
var dialog;
onMounted(async () => {
  dialog = useDialog()
  checkDevice();

  const result = await fieldsList({
    module: 7
  })
  if (result.data) {
    fieldsTitle.value = result.data
  }


  setCodeVerify()

  getNewsList()
});
const pageNum = ref(1)

const handlePageChange = (page) => {
  console.log('当前页:', page)
  getNewsList()
}

const handlePageChange1 = (page) => {
  console.log('当前页:', page)
  getNewsList()

  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // 平滑滚动
  });
}


// 自定义分页主题样式
const paginationThemeOverrides = {

  // 👇 这些是官方支持的 overrides 属性
  itemColor: '#ffffff',                    // 默认背景
  itemColorHover: '#f0f0f0',               // 悬停背景
  itemColorActive: '#00aeff',              // 选中背景（蓝色）
  itemColorActiveHover: '#00aeff',         // 选中悬停
  textColor: '#333333',                    // 默认文字
  textColorActive: '#ffffff',              // ✅ 选中文字颜色（白色）
  itemBorder: '1px solid #d9d9d9',         // 边框
  itemBorderHover: '1px solid #00aeff',    // 悬停边框
  itemBorderActive: '1px solid #00aeff',   // 选中边框

}

function pageNumOnClick(type) {

  if (type == "+") {
    pageNum.value++;
  } else {
    pageNum.value--;
  }

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}
const pageNumOptions = ref([])

function handlePageNumValue(e) {
  console.log("handlePageNumValue", pageNum.value)

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}

const captchaRef = ref(null);

const name = ref("")
const wechat = ref("")
const content = ref("")
const verifyCode = ref("")
async function uploadBoard() {
  const currentCaptchaText = captchaRef.value.captchaText;
  if (currentCaptchaText.toLowerCase() != verifyCode.value.toLowerCase()) {
    dialog.error({
      title: '系统提示',
      content: '验证码输入错误',
      positiveText: '关闭',
      onPositiveClick: () => {
        setCodeVerify()
      }
    })
    return;
  }

  if (name.value.trim() == "") {
    dialog.error({
      title: '系统提示',
      content: '姓名不能为空',
      positiveText: '关闭',
    })
    return;
  }

  if (wechat.value.trim() == "") {
    dialog.error({
      title: '系统提示',
      content: '微信/QQ号不能为空',
      positiveText: '关闭',
    })
    return;
  }

  if (content.value.trim() == "") {
    dialog.error({
      title: '系统提示',
      content: '留言不能为空',
      positiveText: '关闭',
    })
    return;
  }

  //TODO:处理接口
  const data = {
    "para23": name.value,
    "para24": wechat.value,
    "para25": content.value,
    "uuid": myUuid,
    "code": verifyCode.value
  }

  // 1. 创建 FormData 实例
  const formData = new FormData();

  // 2. 添加字段（文本 + 文件）
  formData.append('para23', name.value);
  formData.append('para24', wechat.value);
  formData.append('para25', content.value);
  formData.append('uuid', myUuid);
  formData.append('code', verifyCode.value);


  console.log("uploadBoard", formData)

  const res = await submit(formData)
  console.log("resresresresres", res.code)
  if (res.code == 200) {
    dialog.success({
      title: '系统提示',
      content: res.msg,
      positiveText: '确定',
    })

    name.value = ""
    wechat.value = ""
    content.value = ""
    myUuid = ""
    verifyCode.value = ""
    setCodeVerify()
    window.scrollTo({
      top: 0,
      // behavior: 'smooth'  // 平滑滚动
    });
  }


}

</script>

<style scoped lang="scss">
/* 容器样式 */
.page-content {
  width: 100vw;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;


  @media (min-width: 769px) {
    .page-product {
      padding: 15px 120px;

      .product-title {
        color: #111111;
        font-size: 30px;
        font-weight: bold;
        line-height: 140%;
        margin-bottom: 15px;
      }



      .message-layout {
        display: flex;
        margin-top: 15px;
        background: white;
        padding: 15px 30px;
        min-height: 400px;

        .item-layout {
          display: flex;
          flex-direction: column;
          height: 150px;
          margin-bottom: 15px;
        }


        .item-reply {
          margin-top: 5px;
          background-color: #f3f7f9;
          border: 1px solid #e4eaec;
          color: #111111;
          padding: 20px;
          border-radius: 3px;
        }

        .header-layout {
          width: 100%;
          margin-left: 12px;
          display: flex;



          .item-time {
            display: flex;
            justify-content: end;
            width: 150px;
            font-size: 15px;
            padding-right: 15px;
            color: #0075c1;
            font-weight: bold;
          }

          .item-name {
            margin-top: 5px;
            color: #333333;
            font-size: 18px;
            font-weight: 500;
          }

          .item-descript {
            margin-top: 5px;
            font-size: 15px;
            color: #2a333c;
          }
        }

        .reply-board {
          min-width: 350px;
          flex: 1;

          .reply-title {
            color: #333333;
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
          }
        }



      }

    }
  }

  /* 手机端样式 */
  @media (max-width: 768px) {
    .page-product {
      padding: 15px;


      .product-title {
        color: #111111;
        font-size: 18px;
        font-weight: bold;
        // margin-bottom: 15px;
      }

      .message-layout {
        display: flex;
        flex-direction: column;
        margin-top: 15px;
        background: white;
        padding: 15px;

        .item-layout {
          display: flex;
          flex-direction: column;
          margin-bottom: 15px;
        }


        .item-reply {
          margin-top: 5px;
          background-color: #f3f7f9;
          border: 1px solid #e4eaec;
          color: #111111;
          padding: 10px;
          border-radius: 3px;
        }

        .header-layout {
          width: 100%;
          display: flex;



          .item-time {
            display: flex;
            justify-content: end;
            width: 150px;
            font-size: 15px;
            padding-right: 15px;
            color: #0075c1;
            font-weight: bold;
          }

          .item-name {

            color: #333333;
            font-size: 18px;
            font-weight: 500;
          }


        }

        .item-descript {
          margin-top: 15px;
          font-size: 15px;
          color: #2a333c;
        }

        .reply-board {
          margin-top: 20px;

          .reply-title {
            color: #333333;
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
          }
        }



      }



    }
  }

  :deep(.n-pagination) {
    /* 强制重置所有 Pagination 相关变量 */
    --n-item-text-color-active: #ffffff !important;
    /* ✅ 关键：白色 */
    --n-item-text-color-hover: #333333 !important;

  }


  :deep(.n-list) {
    /* 强制重置所有 Pagination 相关变量 */
    --n-border-color: #e8e4e4 !important;
  }


  .n-list.n-list--bordered .n-list-item,
  .n-list.n-list--hoverable .n-list-item {
    padding: 0px;
  }

  :deep(.n-input .n-input-wrapper) {
    padding-right: 0px !important;
  }


  :deep(.n-input__state-border) {
    --n-border-hover: 1px solid #00aeff !important;
    --n-border-focus: 1px solid #00aeff !important;
  }


}
</style>